/**
 * 
 */
package us.levk.remote.drmaa.client;

import java.io.File;
import java.net.URL;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;

/**
 * @author levk
 *
 */
public abstract class Configuration {

  public interface Credential {
    public String getUserName ();
    public String getPassword ();
  }

  private static final transient Logger LOG = Logger.getLogger (Configuration.class);

  private static final transient Configuration INSTANCE = new Configuration () {

    private final transient XMLConfiguration CONFIGURATION;

    {
      XMLConfiguration config = null;
      try {
        config = new XMLConfiguration (System.getenv ("REMOTE_DRMAA_CLIENT_XML"));
        LOG.info ("Loaded configuration from " + System.getenv ("REMOTE_DRMAA_CLIENT_XML"));
      } catch (ConfigurationException e1) {
        try {
          config = new XMLConfiguration (System.getProperty ("user.home") + File.separator + ".remote-drmaa-client.xml");
          LOG.info ("Loaded configuration from " + System.getProperty ("user.home") + File.separator + ".remote-drmaa-client.xml");
        } catch (ConfigurationException e2) {
          try {
            config = new XMLConfiguration (System.getProperty ("java.home") + File.separator + ".remote-drmaa-client.xml");
            LOG.info ("Loaded configuration from " + System.getProperty ("java.home") + File.separator + ".remote-drmaa-client.xml");
          } catch (ConfigurationException e3) {
            config = new XMLConfiguration ();
            LOG.warn ("Unable to load configuration");
          }
        }
      }
      CONFIGURATION = config;
    }

    public Credential getCredential (URL url) {
      for (final HierarchicalConfiguration c : CONFIGURATION.configurationsAt ("servers.server"))
        if (url.toString ().equals (c.getString ("url")))
          return new Credential () {
            public String getUserName () { return c.getString ("username"); }
            public String getPassword () { return c.getString ("password"); }
          };
      return null;
    }

    public String getContact (URL url) {
      for (HierarchicalConfiguration c : CONFIGURATION.configurationsAt ("servers.server"))
        if (c.getString ("url").equals (url.toString ())) return c.getString ("contact");
      return null;
    }
  };

  public static Configuration getConfiguration () { return INSTANCE; }

  public abstract Credential getCredential (URL url);

  public abstract String getContact (URL url);
}
